package zclients

import (
	"context"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
	"github.com/uber/tchannel-go/thrift"
	"go.didapinche.com/goapi/plat_rocket_api"
	"go.didapinche.com/zeus-go/v2"
	"go.didapinche.com/zeus-go/v2/client"
	"time"
)

func NewRocketMQService(z *zeus.Zeus) (plat_rocket_api.TChanRocketMqService, error) {
	c, err := client.New(z, "RocketMQService")
	if err != nil {
		return nil, errors.Wrap(err, "create zeus RocketMQService error")
	}

	tc := plat_rocket_api.NewTChanRocketMqServiceClient(c)
	return tc, nil
}

func FindGroup(ctx context.Context, appName string, p plat_rocket_api.TChanRocketMqService) (topic string, group string, err error) {
	context2, _ := context.WithTimeout(ctx, 5*time.Second)
	ctx2 := thrift.Wrap(context2)
	page, err := p.FindByEnvAndAppName(ctx2, viper.GetInt32("app.env"), appName)
	if err != nil {
		return topic, group, errors.Wrap(err, "call plat_rocket_api.TChanRocketMqService FindByEnvAndAppName error")
	}
	for _, t := range page.Topics {
		if topic == "" {
			topic = t.Name
		} else {
			topic += "|" + t.Name
		}
	}
	for _, g := range page.Consumers {
		if group == "" {
			group = g.Name
		} else {
			group += "|" + g.Name
		}
	}
	return topic, group, nil
}
